package com.jy.rhin.application.cda;

import com.google.common.collect.Sets;
import com.jy.api.healthreord.HealthRecordAPI;
import com.jy.api.healthreord.dto.jk.JkZhuanzhenJlDto;
import com.jy.common.StringUtil;
import com.jy.framework.base.entity.Result;
import com.jy.rhin.common.Constants;
import com.jy.rhin.domain.cda.CDACreator;
import com.jy.rhin.infra.cda.CDAException;
import com.jy.rhin.model.CodeObject;
import com.jy.rhin.model.ZhuanZhenJL;
import com.jy.rhin.model.body.zhuanzhenjl.*;
import com.jy.rhin.model.header.*;
import com.jy.rhin.utils.CDAUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ZhuanZhenJLApplication {

    private static final String FTL_PATH = "/20zhuanzhenjl.ftl";

    @Resource
    private CDACreator cdaCreator;
    @Autowired
    private HealthRecordAPI healthRecordAPI;
//    @Resource
//    private HospitalService hospitalService;
//    @Resource
//    private DataMigrationAPI dataMigrationAPI;
//    @Resource
//    private HospitalAPI hospitalAPI;

    /**
     * @param zhuanzhendh 转诊单号
     * @param yewujgdm    机构代码(医院)
     */
    public String create(String zhuanzhendh, String yewujgdm) {
        Result<List<JkZhuanzhenJlDto>> result = healthRecordAPI.getByZhuanzhenDhs(yewujgdm, Sets.newHashSet(zhuanzhendh));
        if (!result.isSuccess() || CollectionUtils.isEmpty(result.getData())) {
            throw new CDAException("转诊数据不存在：" + zhuanzhendh + ":" + yewujgdm, null);
        }
        if (CollectionUtils.size(result.getData()) > 1) {
            log.warn("会诊数据发现多条：{}，{}", zhuanzhendh, yewujgdm);
        }

        JkZhuanzhenJlDto zhuanzhenJlDto = result.getData().get(0);

        PatientRole patientRole = this.createPatientRole(zhuanzhenJlDto);
        Author author = this.createAuthor(zhuanzhenJlDto);
        Custodian custodian = this.createCustodian(zhuanzhenJlDto);
        LegalAuthenticator legalAuthenticator = this.createLegalAuthenticator(zhuanzhenJlDto);
        ZhuanZhenParticipant participant = this.createParticipant(zhuanzhenJlDto);
        ZhenDuanJL zhenDuanJL = this.createZhenDuanJL(zhuanzhenJlDto);
        ShiYanShiJCJY shiYanShiJCJY = this.getShiYanShiJCJY();
        YongYao yongYao = this.getYongYao();
        ShouShu shouShu = this.getShouShu();
        JiWangShi jiWangShi = this.getJiWangShi();
        ZhuanZhenJY zhuanZhenJY = this.createZhuanZhenJY(zhuanzhenJlDto);

        ZhuanZhenJL zhuanZhenJL = new ZhuanZhenJL();
        zhuanZhenJL.setEffectiveTime(CDAUtil.toD15(zhuanzhenJlDto.getZhuanzhenrq()));
        zhuanZhenJL.setId(zhuanzhenJlDto.getZhuanzhendh());
        zhuanZhenJL.setPatientRole(patientRole);
        zhuanZhenJL.setAuthor(author);
        zhuanZhenJL.setCustodian(custodian);
        zhuanZhenJL.setLegalAuthenticator(legalAuthenticator);
        zhuanZhenJL.setParticipant(participant);
        zhuanZhenJL.setZhenDuan(zhenDuanJL);
        zhuanZhenJL.setShiYanShiJCJY(shiYanShiJCJY);
        zhuanZhenJL.setYongYao(yongYao);
        zhuanZhenJL.setShouShu(shouShu);
        zhuanZhenJL.setYiXueCZ(this.desigString(null, "无"));
        zhuanZhenJL.setJiWangShi(jiWangShi);
        zhuanZhenJL.setZhuanZhenJY(zhuanZhenJY);
        zhuanZhenJL.setZhiLiaoJH(this.desigString(null, "无"));
        zhuanZhenJL.setJianKangZD(this.desigString(zhuanzhenJlDto.getZhidaojy(), "无"));

        return cdaCreator.create(zhuanZhenJL, FTL_PATH);
    }

    private String desigString(String str) {
        return this.desigString(str, null);
    }

    private String desigString(String str, String replace) {
        replace = StringUtils.isBlank(replace) ? Constants.Sign.HORIZONTAL_LINE : replace;
        return StringUtils.isBlank(str) ? replace : str;
    }

//    public String create(ShuangXiangZZDto shuangXiangZZDto) {
//
//        HospitalDTO zhuanRuHospital = hospitalAPI.info(shuangXiangZZDto.getZhuanRuYYId()).getData();
//        /*Result<HospitalDTO> retzhuanRuHospital = dataMigrationAPI.getByHospitalId(shuangXiangZZDto.getZhuanRuYYId());
//        HospitalDTO zhuanRuHospital = retzhuanRuHospital.getData();*/
//        if (Objects.isNull(zhuanRuHospital)) {
//            throw new CDAException("转入机构数据不存在", null);
//        }
//        log.info("转入机构：" + Serializer.serialize(zhuanRuHospital));
//
//        HospitalDTO zhuanChuHospital = hospitalAPI.info(shuangXiangZZDto.getZhuanChuYYId()).getData();
//        /*Result<HospitalDTO> retzhuanChuHospital = dataMigrationAPI.getByHospitalId(shuangXiangZZDto.getZhuanChuYYId());
//        HospitalDTO zhuanChuHospital = retzhuanChuHospital.getData();*/
//        if (Objects.isNull(zhuanChuHospital)) {
//            throw new CDAException("转出机构数据不存在", null);
//        }
//        log.info("转出机构：" + Serializer.serialize(zhuanChuHospital));
//
//        ZhuanZhenJL zhuanZhenJL = getZhuanZhenJL(shuangXiangZZDto, zhuanRuHospital);
//            BingRenXXDto bingrenxx = patientService.queryPatient(shuangXiangZZDto.getZhengJianHM());
//        zhuanZhenJL.setEffectiveTime(CDAUtil.toD15(shuangXiangZZDto.getZhuanZhenRQ()));
//        zhuanZhenJL.setId(String.valueOf(shuangXiangZZDto.getId()));
//        zhuanZhenJL.setPatientRole(createPatientRole(shuangXiangZZDto));
//        zhuanZhenJL.setAuthor(createAuthor(shuangXiangZZDto));
//        zhuanZhenJL.setCustodian(createCustodian(zhuanChuHospital));
//        zhuanZhenJL.setLegalAuthenticator(createLegalAuthenticator(shuangXiangZZDto));
//        zhuanZhenJL.setParticipant(createParticipant(shuangXiangZZDto, zhuanChuHospital));
//        return cdaCreator.create(zhuanZhenJL, FTL_PATH);
//
//    }

//    private ZhuanZhenJL getZhuanZhenJL(ShuangXiangZZDto shuangXiangZZDto, HospitalDTO zhuanRuHospital) {
//        JSONObject menZhenXX = shuangXiangZZDto.getMenZhenXX();
//        ZhuanZhenJL zhuanZhenJL = new ZhuanZhenJL();
//        zhuanZhenJL.setZhenDuan(getZhenDuanJL(menZhenXX));
//        // 这些信息都没有
//        zhuanZhenJL.setYongYao(getYongYao());
//        zhuanZhenJL.setShiYanShiJCJY(getShiYanShiJCJY());
//        zhuanZhenJL.setShouShu(getShouShu());
//        zhuanZhenJL.setJiWangShi(getJiWangShi());
//        zhuanZhenJL.setZhuanZhenJY(getZhuanZhenJY(shuangXiangZZDto, zhuanRuHospital));
//        // 以下三个全为空
//        zhuanZhenJL.setYiXueCZ("无");
//        zhuanZhenJL.setZhiLiaoJH("无");
//        zhuanZhenJL.setJianKangZD("无");
//        return zhuanZhenJL;
//    }

    private ZhuanZhenJY createZhuanZhenJY(JkZhuanzhenJlDto info) {
        ZhuanZhenJY zhuanZhenJY = new ZhuanZhenJY();
        zhuanZhenJY.setZhuanZhenRQ(CDAUtil.toD8(info.getZhuanzhenrq()));
        zhuanZhenJY.setZhuanZhenYYMS(this.desigString(info.getZhuanzhenyy()));
        zhuanZhenJY.setJieZhenYSXM(this.desigString(info.getJiezhenysxm()));
        zhuanZhenJY.setZhuanRuJGKSMC(this.desigString(info.getZhuanruksmc()));
        zhuanZhenJY.setZhuanRuYLJGDM(this.desigString(info.getZhuanrujgbh()));
        zhuanZhenJY.setZhuanRuYLJGMC(this.desigString(info.getZhuanrujgmc()));
        return zhuanZhenJY;
    }

    private ZhenDuanJL createZhenDuanJL(JkZhuanzhenJlDto info) {
        ZhenDuanJL zhenDuanJL = new ZhenDuanJL();
        zhenDuanJL.setZhenDuanMC(this.desigString(info.getZhenduanmc()));
        zhenDuanJL.setZhenDuanDM(this.desigString(info.getZhenduandm()));
        return zhenDuanJL;
    }

//    private ZhenDuanJL getZhenDuanJL(JSONObject menZhenXX) {
//        if (!StringUtil.isNullOrEmpty(menZhenXX.getString("zhenDuanMC1")) &&
//                !StringUtil.isNullOrEmpty(menZhenXX.getString("zhenDuanDM1"))) {
//            ZhenDuanJL zhenDuanJL = new ZhenDuanJL();
//            zhenDuanJL.setZhenDuanMC(menZhenXX.getString("zhenDuanMC1"));
//            zhenDuanJL.setZhenDuanDM(menZhenXX.getString("zhenDuanDM1"));
//            return zhenDuanJL;
//        }
//        return null;
//    }

    private ShiYanShiJCJY getShiYanShiJCJY() {
//        ShiYanShiJCJY shiYanShiJCJY = new ShiYanShiJCJY();
        return null;
    }

    private YongYao getYongYao() {
//        YongYao yongYao = new YongYao();
        return null;
    }

    private ShouShu getShouShu() {
//        ShouShu shouShu = new ShouShu();
        return null;
    }

    private JiWangShi getJiWangShi() {
//        JiWangShi jiWangShi = new JiWangShi();
        return null;
    }

//    private ZhuanZhenJY getZhuanZhenJY(ShuangXiangZZDto shuangXiangZZDto, HospitalDTO zhuanRuHospital) {
//        ZhuanZhenJY zhuanZhenJY = new ZhuanZhenJY();
//        zhuanZhenJY.setZhuanZhenRQ(CDAUtil.toD8(shuangXiangZZDto.getZhuanZhenRQ()));
//        zhuanZhenJY.setZhuanZhenYYMS(shuangXiangZZDto.getZhuanZhenYYMC());
//        zhuanZhenJY.setJieZhenYSXM(StringUtil.isNullOrEmpty(shuangXiangZZDto.getZhuanRuYSMC()) ? "无" : shuangXiangZZDto.getZhuanRuYSMC());
//        zhuanZhenJY.setZhuanRuJGKSMC(shuangXiangZZDto.getZhuanRuKS());
//
//        zhuanZhenJY.setZhuanRuYLJGDM(zhuanRuHospital.getOutId());
//        zhuanZhenJY.setZhuanRuYLJGMC(shuangXiangZZDto.getZhuanRuYYMC());
//        return zhuanZhenJY;
//    }

    private String toLength17(String str) {
        if (str.length() < 17) {
            return StringUtil.padRight(str, 17, '0');
        }
        return str.substring(0, 17);
    }

    private PatientRole createPatientRole(JkZhuanzhenJlDto info) {
        PatientRole patientRole = new PatientRole();
        patientRole.setId(toLength17(info.getGerendabs()));
        patientRole.setZhuYuanHBS(this.desigString(null));

        Patient patient = new Patient();
        patient.setName(info.getXingming());
        patient.setId(info.getShenfenzh());
        patient.setAdministrativeGender(new CodeObject(info.getXingbie().toString(), info.getXingbiemc()));
        patient.setBirthTime(info.getChushengrq() == null ? null : CDAUtil.toD8(info.getChushengrq()));
        patient.setTelecom(this.desigString(info.getHuanzhelxdh()));
        patientRole.setPatient(patient);

        Addr addr = new Addr();
        addr.setState(this.desigString(info.getJiatindzsfmc()));
        addr.setCity(this.desigString(info.getJiatindzsmc()));
        addr.setCounty(this.desigString(info.getJiatindzxmc()));
        addr.setTownship(this.desigString(info.getJiatindzxzmc()));
        addr.setStreetName(this.desigString(info.getJiatindzsqmc()));
        addr.setHouseNumber(this.desigString(info.getJiatindzqtdz()));
        patientRole.setAddr(addr);
        return patientRole;
    }

//    PatientRole createPatientRole(ShuangXiangZZDto info) {
//        PatientRole patientRole = new PatientRole();
//        patientRole.setId(toLength17(String.valueOf(info.getBingRenId())));
//        patientRole.setZhuYuanHBS("-");
//        patientRole.setPatient(createPatient(info));
//
//        Addr addr = new Addr();
//        addr.setState("广东省");
//        addr.setCity("深圳市");
//        addr.setCounty("南山区");
//        addr.setTownship("南油A区");
//        addr.setStreetName("2-3单元");
//        addr.setHouseNumber("404");
//        patientRole.setAddr(addr);
//        return patientRole;
//    }

//    Patient createPatient(ShuangXiangZZDto info) {
//        Patient patient = new Patient();
//        patient.setName(info.getBingRenXM());
//        patient.setId(info.getZhengJianHM());
//        if (!StringUtil.isNullOrEmpty(info.getXingBieDM())) {
//            String xingBieMC = info.getXingBieMC();
//            if ("男".equals(xingBieMC)) {
//                xingBieMC = "男性";
//            } else if ("女".equals(xingBieMC)) {
//                xingBieMC = "女性";
//            }
//            if ("男性".equals(xingBieMC)) {
//                info.setXingBieDM("1");
//            } else if ("女性".equals(xingBieMC)) {
//                info.setXingBieDM("2");
//            } else {
//                info.setXingBieDM("0");
//            }
//            patient.setAdministrativeGender(new CodeObject(info.getXingBieDM(), xingBieMC));
//        }
//        if (info.getChuShengRQ() != null) {
//            patient.setBirthTime(CDAUtil.toD8(info.getChuShengRQ()));
//        }
////        patient.setMaritalStatus(new CodeObject(info.getHUNYINZKDM(), info.getHUNYINZKMC()));
////        patient.setEmployerOrganization(info.getGONGZUODW());
//        patient.setTelecom(info.getLianXiDH());
//
////        Addr addr = new Addr();
////        addr.setState(info.getHUKOUDZSFMC());
////        addr.setCity(info.getHUKOUDZSMC());
////        addr.setCounty(info.getHUKOUDZXMC());
////        addr.setTownship(info.getHUKOUDZXZMC());
////        addr.setStreetName(info.getHUKOUDZSQMC());
////        patient.setHouseholdAddr(addr);
//
//        //todo 获取学历名称
////        if (!StringUtil.isNullOrEmpty(info.getXUELIDM())) {
////            patient.setEducationLevel(new CodeObject(info.getXUELIDM(), info.getWENHUACDMC()));
////        }
////        if (!StringUtil.isNullOrEmpty(info.getZHIYELBDM())) {
////            patient.setOccupation(new CodeObject(info.getZHIYELBDM(), info.getZHIYEMC()));
////        }
//        return patient;
//    }

    private Custodian createCustodian(JkZhuanzhenJlDto info) {
        Custodian custodian = new Custodian();
        custodian.setId(info.getYewujgoutid());
        custodian.setName(info.getYewujgmc());
        custodian.setAddr(this.desigString(info.getYewujgdz()));
        return custodian;
    }

//    Custodian createCustodian(HospitalDTO hospital) {
//        Custodian custodian = new Custodian();
//        custodian.setId(hospital.getOutId());
//        custodian.setName(hospital.getName());
//        custodian.setAddr(hospital.getAddress());
//        return custodian;
//    }

    private Author createAuthor(JkZhuanzhenJlDto info) {
        Author author = new Author();
        author.setId(info.getZhuanzhenys());
        author.setTime(CDAUtil.toD15(info.getZhuanzhenrq()));
        author.setName(info.getZhuanzhenysxm());
        author.setOrganizationId(info.getYewujgoutid());
        author.setOrganizationName(info.getYewujgmc());
        author.setOrganizationAddr(this.desigString(info.getYewujgdz()));
        return author;
    }

//    Author createAuthor(ShuangXiangZZDto info) {
//        Author author = new Author();
//        author.setId(info.getCaoZuoRBM());
//        author.setTime(CDAUtil.toD15(info.getZhuanZhenRQ()));
//        author.setName(info.getCaoZuoRMC());
//        HospitalDTO hospitalDTO = hospitalAPI.info(info.getZhuanChuYYId()).getData();
////        HospitalDTO hospitalDTO = dataMigrationAPI.getByHospitalId(info.getZhuanChuYYId()).getData();
//        author.setOrganizationId(hospitalDTO.getOutId());
//        author.setOrganizationName(info.getZhuanChuYYMC());
////        author.setOrganizationAddr(hospital.getAddress());
//        return author;
//    }

    private LegalAuthenticator createLegalAuthenticator(JkZhuanzhenJlDto info) {
        LegalAuthenticator legalAuthenticator = new LegalAuthenticator();
        legalAuthenticator.setTime(CDAUtil.toD8(info.getChuangjiansj()));
        legalAuthenticator.setName(info.getZhuanzhenysxm());
        return legalAuthenticator;
    }

//    private LegalAuthenticator createLegalAuthenticator(ShuangXiangZZDto shuangXiangZZDto) {
//        LegalAuthenticator legalAuthenticator = new LegalAuthenticator();
//        legalAuthenticator.setTime(CDAUtil.toD8(shuangXiangZZDto.getChuangJianSJ()));
//        legalAuthenticator.setName(shuangXiangZZDto.getCaoZuoRMC());
//        return legalAuthenticator;
//    }

    private ZhuanZhenParticipant createParticipant(JkZhuanzhenJlDto info) {
        ZhuanZhenParticipant participant = new ZhuanZhenParticipant();
        participant.setName(info.getZhuanzhenysxm());
        participant.setTelecom(info.getZhuanzhenysdh());
        participant.setZhuanZhenJGDM(info.getYewujgdm());
        participant.setZhuanZhenJGMC(info.getYewujgmc());
        return participant;
    }

//    private ZhuanZhenParticipant createParticipant(ShuangXiangZZDto shuangXiangZZDto, HospitalDTO zhuanChuHospital) {
//        ZhuanZhenParticipant participant = new ZhuanZhenParticipant();
//        participant.setName(shuangXiangZZDto.getCaoZuoRMC());
//        participant.setTelecom(shuangXiangZZDto.getCaoZuoRDH());
//        participant.setZhuanZhenJGDM(zhuanChuHospital.getOutId());
//        participant.setZhuanZhenJGMC(zhuanChuHospital.getName());
//        return participant;
//    }
}